'use strict';

/* App Module */

var fulboApp = angular.module('fulboApp', [
  'ngRoute',
  'fulboAnimations',
  'fulboControllers',
  'fulboFilters',
  'fulboServices',
  'fulboDirectives',
  'flow'
]);

fulboApp.value('redirectToUrlAfterLogin', { url: '/' });

fulboApp.config(['$routeProvider', '$locationProvider', 'flowFactoryProvider', 
  function($routeProvider, $locationProvider, flowFactoryProvider) {
    $routeProvider.
      when('/', {
        templateUrl: 'partials/home.html',
        controller: 'HomeController'
      }).
      when('/match/:matchId', {
        templateUrl: 'partials/match.html',
        controller: 'MatchController'
      }).
	  when('/matches', {
        templateUrl: 'partials/matches.html',
        controller: 'MatchesController'
      }).
	  when('/group/:groupId', {
        templateUrl: 'partials/group.html',
        controller: 'GroupController'
      }).
	  when('/groups', {
        templateUrl: 'partials/groups.html',
        controller: 'GroupsController'
      }).
	  when('/profile', {
        templateUrl: 'partials/profile.html',
        controller: 'ProfileController'
      }).
      otherwise({
        redirectTo: '/'
      });
    
    //$locationProvider.html5Mode(true);
    
    flowFactoryProvider.defaults = {
    	target: 'upload.php',
        permanentErrors: [404, 500, 501],
        maxChunkRetries: 1,
        chunkRetryInterval: 5000,
        simultaneousUploads: 4,
        singleFile: true
    };
    flowFactoryProvider.on('catchAll', function (event) {
    	console.log('catchAll', arguments);
    });
  }]);

fulboApp.run(['$rootScope', '$window', '$location', 'Fields', 'Matches', 'MatchTypes', 'UsersAuth', 
     	function($rootScope, $window, $location, Fields, Matches, MatchTypes, UserAuth) {

		$rootScope.routeChanges = 0;
	
		$rootScope.fbUser = null;
		$rootScope.user = null;
		
		$rootScope.fbAppId = "1454310071508137";
		$rootScope.activePage = "home";
		
		$rootScope.fields = Fields.query();
		$rootScope.matchTypes = MatchTypes.query();
		
		$rootScope.createMatchModal = function(){
	    	var date = moment($("#matchModalDate").val(), "DD/MM/YYYY").format('YYYY-MM-DD');
		    var dateTime = date + " " + $("#matchModalHour").val();
		    var fieldId = $("#matchModalField").val();
		    var matchTypeId = $("#matchModalType").val();
		    var admin_userId = $rootScope.user.id;
			
		    if(date == "Invalid date") {
		    	showAlert("Error", "Debe elegir una fecha válida para el partido.");
		    	return false;
		    }
		    if(dateTime == "Invalid date") {
		    	showAlert("Error", "Debe elegir una hora válida para el partido.");
		    	return false;
		    }
		    if(fieldId == null) {
		    	showAlert("Error", "Debe elegir una sede para el partido.");
		    	return false;
		    }
		    if(matchTypeId == null) {
		    	showAlert("Error", "Debe elegir la cantidad de jugadores.");
		    	return false;
		    }
		    
		    var match = {
		    	date: dateTime,
		    	fieldId: fieldId,
		    	comments: "",
		        cancelled: 0,
		    	matchTypeId: matchTypeId,
		    	admin_userId: admin_userId
		    };
		    
		    $('#newMatchModal').modal('hide');
			Matches.save(match, function(newMatch){
		    	console.log("Match saved, id:" + newMatch.id);
		    	$location.path( "match/" + newMatch.id );
		    }, function(){
		    	console.log("Failed saving match!");
		    	showAlert("Error", "Hubo un error al crear el partido! Intente nuevamente.");
		    });
	    };
		
		$rootScope.$on('$routeChangeStart', function (event, next) {
			if($rootScope.routeChanges == 0){
				UserAuth.saveAttemptUrl();
				var token = getURLParameter('token');
				$rootScope.matchToken = token;
			}
			
			if (!UserAuth.isLogged) {
				
		    	event.preventDefault();
		    	$location.path( "/" );
		    	$rootScope.routeChanges++;
		    }
		});
		
		$window.fbAsyncInit = function() {
     		// Executed when the SDK is loaded

     		FB.init({ 
     			appId: $rootScope.fbAppId, 
     			channelUrl: 'channel.html', 
     			status: true, 
     			cookie: true, 
     			xfbml: true 
     		});
     		UserAuth.watchAuthenticationStatusChange();
     		
     		$("#loaderDiv").hide();
     	};

     	// Are you familiar to IIFE ( http://bit.ly/iifewdb ) ?

     	(function(d){
     		// load the Facebook javascript SDK

     		var js, 
     		id = 'facebook-jssdk', 
     		ref = d.getElementsByTagName('script')[0];

     		if (d.getElementById(id)) {
     			return;
     		}

     		js = d.createElement('script'); 
     		js.id = id; 
     		js.async = true;
     		js.src = "//connect.facebook.net/en_US/all.js";

     		ref.parentNode.insertBefore(js, ref);

     	}(document));

     }]);